from django.http import HttpResponse
from django.shortcuts import render, render_to_response
from django.template import RequestContext
import djangotest.HelloWorld.mtcnn_client as mtcnn_client
import argparse
import tensorflow as tf
import traceback


def hello(request):
    context = {}
    context['hello'] = 'Hello World!'
    return render(request, 'hello.html', context)

def index(request):
    return render(request, 'index.html')
    # return render_to_response('hello.html',{},context_instance=RequestContext(request))

import uuid,os
def generateUUID(filename): # 创建唯一的文件名
    id = str(uuid.uuid4())
    extend = os.path.splitext(filename)[1]
    return id+extend
def parse_arguments(argv):
    parser = argparse.ArgumentParser()

    parser.add_argument('--image_path', type=str, help='Unaligned face images.', default=r'E:\testDir\ml\detect_face.jpg')
    parser.add_argument('--output_dir', type=str, help='Test MTCNN output dir',
                        default=r'E:\testDir\ml\mtcnn_output')
    parser.add_argument('--image_size', type=int, help='Image size (height, width) in pixels.', default=182)
    parser.add_argument('--margin', type=int,
                        help='Margin for the crop around the bounding box (height, width) in pixels.', default=44)
    parser.add_argument('--random_order',
                        help='Shuffles the order of images to enable alignment using multiple processes.',
                        action='store_true')
    parser.add_argument('--gpu_memory_fraction', type=float,
                        help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0)
    parser.add_argument('--detect_multiple_faces', type=bool,
                        help='Detect and align multiple faces per image.', default=False)

    return parser.parse_args(argv)
def detect(request):
    try:
        file = request.FILES.get('image')

        if not file:
            return HttpResponse("no files for upload!")
        file.name = generateUUID(file.name)  # 调用自定义的generateUUID生成唯一文件名
        print(file)
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        imagepath = os.path.join(BASE_DIR,'static/images')
        if not os.path.exists(imagepath):
            os.makedirs(imagepath)
        file_path = os.path.join(imagepath, file.name)
        print(file_path)
        with open(file_path, 'wb') as f:
            for chunk in file.chunks():
                f.write(chunk)
        fileresult = mtcnn_client.detect(parse_arguments(['--image_path=' + file_path]))
        with open(fileresult, 'rb') as f:
            content = f.read()
        return HttpResponse(content, content_type=file.content_type)
    except Exception as err:
        traceback.print_exc()
        return HttpResponse("上传失败")